package com.onlinelibrary.activities.web;

import android.annotation.SuppressLint;
import android.app.Application;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;

import com.onlinelibrary.activities.App;
import com.onlinelibrary.databinding.ActivityWebBinding;
import com.onlinelibrary.utils.Http;

public class WebVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private static WebView web;
    private static ActivityWebBinding binding;
    @SuppressLint("StaticFieldLeak")
    private static WebActivity webActivity;
    private boolean isFinish=false;

    public WebVM(@NonNull Application application) {
        super(application);
    }
    @SuppressLint("SetJavaScriptEnabled")
    @BindingAdapter("bindWeb")
    public static void bindWeb(WebView webView,WebVM webVM){
        web=webView;
        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setDomStorageEnabled(true);
        web.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                if(url.endsWith("profile/")) view.loadUrl("javascript:window.java_obj.onSignin(document.documentElement.outerHTML);void(0)");
                else if(url.endsWith("signup/")||url.endsWith("login/")) view.loadUrl("javascript:window.java_obj.onSignout(document.documentElement.outerHTML);void(0)");
                super.onPageFinished(view, url);
            }
        });
        web.getSettings().setAllowFileAccessFromFileURLs(true);
        web.loadUrl(App.url);
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            if (web.canGoBack()){
                web.goBack();
                isFinish=false;
            }else {
                web.loadUrl(Http.BASE_URL+"admin/logout");
                isFinish=true;
            }
            if (isFinish){
                webActivity.finish();
            }
        }
        return true;
    }

    public void setBinding(ActivityWebBinding binding, WebActivity webActivity) {
        WebVM.binding=binding;
        WebVM.webActivity=webActivity;
    }
}